<template>
  <div class="album-detail-page">
    <AppHeader />
    <div class="album-detail-container">
      <AppSidebar />
      <div class="album-detail-content" v-if="album">
        <!-- 相册头部信息 -->
        <div class="album-header">
          <div class="album-cover">
            <img 
              :src="albumCoverUrl" 
              :alt="album.name"
              @error="handleCoverError"
            />
          </div>
          
          <div class="album-info">
            <h1>{{ album.name }}</h1>
            <p v-if="album.description">{{ album.description }}</p>
            <div class="album-meta">
              <span>{{ album.photo_count || 0 }} 张照片</span>
              <span>创建于 {{ formatDate(album.created_at) }}</span>
              <span>更新于 {{ formatDate(album.updated_at) }}</span>
            </div>
            
            <div class="album-actions">
              <el-button @click="editAlbum" :icon="Edit">编辑相册</el-button>
              <el-button @click="addPhotosToAlbum" :icon="Plus">添加照片</el-button>
              <el-button @click="startSlideshow" :icon="VideoPlay">幻灯片播放</el-button>
              <el-button type="danger" @click="confirmDeleteAlbum" :icon="Delete">删除相册</el-button>
            </div>
          </div>
        </div>
        
        <!-- 照片工具栏 -->
        <PhotoToolbar 
          :view-mode="viewMode"
          :selected-photos="selectedPhotos"
          @view-change="handleViewChange"
          @select-all="selectAllPhotos"
          @deselect-all="deselectAllPhotos"
          @add-to-album="handleAddToAlbum"
          @remove-from-album="handleRemoveFromAlbum"
          @delete-selected="confirmDeleteSelected"
        />
        
        <!-- 照片列表 -->
        <div class="album-photos">
          <PhotoView 
            :photos="albumPhotos"
            :view-mode="viewMode"
            :selectable="true"
            @photo-click="handlePhotoClick"
            @photo-select="handlePhotoSelect"
            @photo-deselect="handlePhotoDeselect"
          />
          
          <!-- 分页 -->
          <PhotoPagination 
            :current-page="currentPage"
            :page-size="pageSize"
            :total="totalPhotos"
            @page-change="handlePageChange"
          />
        </div>
      </div>
      
      <!-- 加载状态 -->
      <div v-else-if="loading" class="album-loading-container">
        <el-icon class="is-loading"><Loading /></el-icon>
        <span>加载相册详情中...</span>
      </div>
      
      <!-- 错误状态 -->
      <div v-else class="album-error-container">
        <el-result
          icon="error"
          title="加载失败"
          sub-title="无法加载相册详情，请稍后重试"
        >
          <template #extra>
            <el-button type="primary" @click="goBack">返回</el-button>
          </template>
        </el-result>
      </div>
    </div>
    
    <!-- 编辑相册对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑相册"
      width="500px"
    >
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="相册名称">
          <el-input v-model="editForm.name" placeholder="请输入相册名称" />
        </el-form-item>
        <el-form-item label="相册描述">
          <el-input 
            v-model="editForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入相册描述"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAlbum">保存</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 添加照片对话框 -->
    <el-dialog
      v-model="addPhotosDialogVisible"
      title="添加照片到相册"
      width="80%"
      top="5vh"
    >
      <div class="add-photos-content">
        <!-- 搜索栏 -->
        <div class="photos-search">
          <el-input
            v-model="photosSearchQuery"
            placeholder="搜索照片..."
            @input="searchPhotos"
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <!-- 照片列表 -->
        <div class="photos-selection">
          <div class="photos-grid">
            <div 
              v-for="photo in availablePhotos"
              :key="photo.id"
              class="photo-item"
              :class="{ selected: selectedPhotosToAdd.includes(photo.id) }"
              @click="togglePhotoSelection(photo.id)"
            >
              <img :src="photo.thumbnail_path" :alt="photo.file_name" />
              <div class="photo-overlay">
                <el-icon v-if="selectedPhotosToAdd.includes(photo.id)" class="check-icon">
                  <Check />
                </el-icon>
              </div>
            </div>
          </div>
          
          <!-- 分页 -->
          <el-pagination
            v-model:current-page="availablePhotosPage"
            :page-size="availablePhotosPageSize"
            :total="availablePhotosTotal"
            layout="prev, pager, next"
            @current-change="loadAvailablePhotos"
          />
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addPhotosDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmAddPhotos"
            :disabled="selectedPhotosToAdd.length === 0"
          >
            添加照片 ({{ selectedPhotosToAdd.length }})
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Edit, 
  Plus, 
  VideoPlay, 
  Delete, 
  Loading, 
  Search, 
  Check 
} from '@element-plus/icons-vue'
import { useAlbumStore } from '../stores/album'
import { usePhotoStore } from '../stores/photo'
import { Album, Photo } from '../types'
import AppHeader from '../components/common/AppHeader.vue'
import AppSidebar from '../components/common/AppSidebar.vue'
import PhotoToolbar from '../components/photo/PhotoToolbar.vue'
import PhotoView from '../components/photo/PhotoView.vue'
import PhotoPagination from '../components/photo/PhotoPagination.vue'
import { formatDate } from '../utils/date'

const route = useRoute()
const router = useRouter()
const albumStore = useAlbumStore()
const photoStore = usePhotoStore()

// 状态
const loading = ref(true)
const albumId = computed(() => route.params.id as string)
const album = computed(() => albumStore.currentAlbum)
const albumPhotos = computed(() => albumStore.albumPhotos)
const currentPage = ref(1)
const pageSize = ref(20)
const totalPhotos = computed(() => albumStore.albumPhotosTotal)
const viewMode = ref('grid')
const selectedPhotos = ref<number[]>([])

// 编辑相册对话框
const editDialogVisible = ref(false)
const editForm = ref({
  name: '',
  description: ''
})

// 添加照片对话框
const addPhotosDialogVisible = ref(false)
const photosSearchQuery = ref('')
const availablePhotos = ref<Photo[]>([])
const availablePhotosPage = ref(1)
const availablePhotosPageSize = ref(20)
const availablePhotosTotal = ref(0)
const selectedPhotosToAdd = ref<number[]>([])

// 计算属性
const albumCoverUrl = computed(() => {
  if (!album.value) return ''
  
  // 如果有封面照片，使用封面照片的缩略图
  if (album.value.cover_photo_id) {
    const coverPhoto = albumPhotos.value.find(p => p.id === album.value.cover_photo_id)
    if (coverPhoto && coverPhoto.thumbnail_path) {
      return coverPhoto.thumbnail_path
    }
  }
  
  // 否则使用第一张照片的缩略图
  if (albumPhotos.value.length > 0 && albumPhotos.value[0].thumbnail_path) {
    return albumPhotos.value[0].thumbnail_path
  }
  
  // 默认封面
  return '/images/default-album-cover.png'
})

// 生命周期钩子
onMounted(async () => {
  await loadAlbumDetail()
})

// 监听相册ID变化
watch(albumId, async () => {
  if (albumId.value) {
    await loadAlbumDetail()
  }
})

// 加载相册详情
const loadAlbumDetail = async () => {
  if (!albumId.value) return
  
  loading.value = true
  
  try {
    // 获取相册详情
    await albumStore.getAlbumById(parseInt(albumId.value))
    
    if (album.value) {
      // 初始化编辑表单
      editForm.value = {
        name: album.value.name,
        description: album.value.description || ''
      }
      
      // 获取相册照片
      await loadAlbumPhotos()
    }
  } catch (error) {
    console.error('加载相册详情失败:', error)
    ElMessage.error('加载相册详情失败')
  } finally {
    loading.value = false
  }
}

// 加载相册照片
const loadAlbumPhotos = async () => {
  if (!album.value) return
  
  try {
    await albumStore.getAlbumPhotos(
      album.value.id,
      currentPage.value,
      pageSize.value
    )
  } catch (error) {
    console.error('加载相册照片失败:', error)
    ElMessage.error('加载相册照片失败')
  }
}

// 封面图片错误处理
const handleCoverError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = '/images/default-album-cover.png'
}

// 返回上一页
const goBack = () => {
  router.push('/albums')
}

// 编辑相册
const editAlbum = () => {
  editDialogVisible.value = true
}

// 保存相册
const saveAlbum = async () => {
  if (!album.value) return
  
  try {
    await albumStore.updateAlbum(album.value.id, {
      name: editForm.value.name,
      description: editForm.value.description
    })
    
    editDialogVisible.value = false
    ElMessage.success('相册已更新')
  } catch (error) {
    console.error('更新相册失败:', error)
    ElMessage.error('更新相册失败')
  }
}

// 添加照片到相册
const addPhotosToAlbum = async () => {
  if (!album.value) return
  
  // 重置状态
  selectedPhotosToAdd.value = []
  availablePhotosPage.value = 1
  photosSearchQuery.value = ''
  
  // 加载可用照片
  await loadAvailablePhotos()
  
  // 显示对话框
  addPhotosDialogVisible.value = true
}

// 加载可用照片
const loadAvailablePhotos = async () => {
  try {
    // 这里应该调用获取不在当前相册中的照片的API
    // 暂时使用所有照片
    await photoStore.getPhotoList({
      page: availablePhotosPage.value,
      pageSize: availablePhotosPageSize.value,
      query: photosSearchQuery.value
    })
    
    availablePhotos.value = photoStore.photos
    availablePhotosTotal.value = photoStore.total
  } catch (error) {
    console.error('加载可用照片失败:', error)
    ElMessage.error('加载可用照片失败')
  }
}

// 搜索照片
const searchPhotos = async () => {
  availablePhotosPage.value = 1
  await loadAvailablePhotos()
}

// 切换照片选择状态
const togglePhotoSelection = (photoId: number) => {
  const index = selectedPhotosToAdd.value.indexOf(photoId)
  if (index > -1) {
    selectedPhotosToAdd.value.splice(index, 1)
  } else {
    selectedPhotosToAdd.value.push(photoId)
  }
}

// 确认添加照片
const confirmAddPhotos = async () => {
  if (!album.value || selectedPhotosToAdd.value.length === 0) return
  
  try {
    // 这里应该调用批量添加照片到相册的API
    for (const photoId of selectedPhotosToAdd.value) {
      await albumStore.addPhotoToAlbum(album.value.id, photoId)
    }
    
    addPhotosDialogVisible.value = false
    ElMessage.success(`已添加 ${selectedPhotosToAdd.value.length} 张照片到相册`)
    
    // 重新加载相册照片
    await loadAlbumPhotos()
  } catch (error) {
    console.error('添加照片到相册失败:', error)
    ElMessage.error('添加照片到相册失败')
  }
}

// 开始幻灯片播放
const startSlideshow = () => {
  if (!album.value || albumPhotos.value.length === 0) {
    ElMessage.warning('相册中没有照片')
    return
  }
  
  // 这里应该实现幻灯片播放功能
  ElMessage.info('幻灯片播放功能待实现')
}

// 确认删除相册
const confirmDeleteAlbum = async () => {
  if (!album.value) return
  
  try {
    await ElMessageBox.confirm(
      `确定要删除相册 "${album.value.name}" 吗？此操作不会删除照片，但会从相册中移除所有照片。`,
      '删除相册',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 用户确认，执行删除
    await deleteAlbum()
  } catch {
    // 用户取消
    ElMessage.info('已取消删除相册')
  }
}

// 删除相册
const deleteAlbum = async () => {
  if (!album.value) return
  
  try {
    await albumStore.deleteAlbum(album.value.id)
    ElMessage.success('相册已删除')
    
    // 返回相册列表
    router.push('/albums')
  } catch (error) {
    console.error('删除相册失败:', error)
    ElMessage.error('删除相册失败')
  }
}

// 视图模式变更处理
const handleViewChange = (mode: string) => {
  viewMode.value = mode
}

// 全选照片
const selectAllPhotos = () => {
  selectedPhotos.value = albumPhotos.value.map(photo => photo.id)
}

// 取消全选
const deselectAllPhotos = () => {
  selectedPhotos.value = []
}

// 照片点击处理
const handlePhotoClick = (photo: Photo) => {
  router.push(`/photos/${photo.id}`)
}

// 照片选择处理
const handlePhotoSelect = (photoId: number) => {
  if (!selectedPhotos.value.includes(photoId)) {
    selectedPhotos.value.push(photoId)
  }
}

// 照片取消选择处理
const handlePhotoDeselect = (photoId: number) => {
  const index = selectedPhotos.value.indexOf(photoId)
  if (index > -1) {
    selectedPhotos.value.splice(index, 1)
  }
}

// 添加到其他相册
const handleAddToAlbum = async () => {
  if (selectedPhotos.value.length === 0) {
    ElMessage.warning('请先选择照片')
    return
  }
  
  // 这里应该实现添加到其他相册的功能
  ElMessage.info('添加到其他相册功能待实现')
}

// 从相册移除
const handleRemoveFromAlbum = async () => {
  if (!album.value || selectedPhotos.value.length === 0) {
    ElMessage.warning('请先选择照片')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要从相册中移除选中的 ${selectedPhotos.value.length} 张照片吗？`,
      '移除照片',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 用户确认，执行移除
    for (const photoId of selectedPhotos.value) {
      await albumStore.removePhotoFromAlbum(album.value.id, photoId)
    }
    
    ElMessage.success(`已从相册移除 ${selectedPhotos.value.length} 张照片`)
    
    // 清空选择
    selectedPhotos.value = []
    
    // 重新加载相册照片
    await loadAlbumPhotos()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('从相册移除照片失败:', error)
      ElMessage.error('从相册移除照片失败')
    }
  }
}

// 确认删除选中的照片
const confirmDeleteSelected = async () => {
  if (selectedPhotos.value.length === 0) {
    ElMessage.warning('请先选择照片')
    return
  }
  
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedPhotos.value.length} 张照片吗？此操作不可恢复。`,
      '删除照片',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    // 用户确认，执行删除
    for (const photoId of selectedPhotos.value) {
      await photoStore.deletePhoto(photoId)
    }
    
    ElMessage.success(`已删除 ${selectedPhotos.value.length} 张照片`)
    
    // 清空选择
    selectedPhotos.value = []
    
    // 重新加载相册照片
    await loadAlbumPhotos()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除照片失败:', error)
      ElMessage.error('删除照片失败')
    }
  }
}

// 分页处理
const handlePageChange = async (page: number) => {
  currentPage.value = page
  await loadAlbumPhotos()
}
</script>

<style scoped>
.album-detail-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.album-detail-container {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.album-detail-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: var(--el-bg-color-page);
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 相册头部样式 */
.album-header {
  display: flex;
  gap: 20px;
  background-color: var(--el-bg-color);
  border-radius: 8px;
  padding: 20px;
  box-shadow: var(--el-box-shadow-light);
}

.album-cover {
  width: 200px;
  height: 200px;
  border-radius: 8px;
  overflow: hidden;
  flex-shrink: 0;
}

.album-cover img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.album-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.album-info h1 {
  margin: 0;
  font-size: 24px;
}

.album-info p {
  margin: 0;
  color: var(--el-text-color-regular);
}

.album-meta {
  display: flex;
  gap: 16px;
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.album-actions {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-top: auto;
}

/* 照片列表样式 */
.album-photos {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 加载和错误状态 */
.album-loading-container,
.album-error-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 50vh;
  gap: 16px;
}

/* 添加照片对话框样式 */
.add-photos-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
  height: 70vh;
}

.photos-search {
  flex-shrink: 0;
}

.photos-selection {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 16px;
  overflow: hidden;
}

.photos-grid {
  flex: 1;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 8px;
  overflow-y: auto;
}

.photo-item {
  position: relative;
  aspect-ratio: 1;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  transition: transform 0.2s;
}

.photo-item:hover {
  transform: scale(1.05);
}

.photo-item.selected {
  border: 2px solid var(--el-color-primary);
}

.photo-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.photo-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.2s;
}

.photo-item.selected .photo-overlay {
  opacity: 1;
}

.check-icon {
  color: white;
  font-size: 24px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .album-header {
    flex-direction: column;
  }
  
  .album-cover {
    width: 100%;
    height: 200px;
  }
  
  .album-actions {
    flex-direction: column;
  }
  
  .photos-grid {
    grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
  }
}
</style>